/**
 * @author Qi
 */
function DataManager(){
	this.contacts = null;
	this.init = function(){
		this.contacts = new Array();
		this.restoreContacts();
	};
	this.restoreContacts = function(){
		var storedContacts = dojox.storage.get("js_contact_manager_contacts");
		if(storedContacts){
			var splitContacts = storedContacts.split("~>!<~");
			for(var i = 0;i < splitContacts.length;i++){
				var contact = new Contact();
				contact.restoreFromJson(splitContacts[i]);
				contact.arrayIndex = i;
				this.contacts.push(contact);
			}
		}
	};
	this.saveContact = function(inContact,inIndex){
		if(inIndex == -1){
			inContact.arrayIndex = this.contacts.length;
			this.contacts.push(inContact);
		}else{
			this.contacts[inIndex] = inContact;
		}
		this.persistContacts();
	};
	this.persistContacts = function(){
		var contactsString = "";
		for(var i = 0;i < this.contacts.length;i++){
			if(contactsString != ""){
				contactsString += "~>!<~";
			}
			contactsString += this.contacts[i];
		}
		try{
			dojox.storage.put("js_contact_manager_contacts",contactsString,this.saveHandler);
		}catch(e){alert(e);}
	};
	this.saveHandler = function(status,keyName){
		if(status == dojox.storage.FAILED){
			alert("A failure occurred saving contact to persistent storage");
		}
	};
	this.deleteContact = function(inIndex){
		this.contacts.splice(inIndex,1);
		this.persistContacts();
		for(var i = 0;i < this.contacts.length;i++){
			this.contacts[i].arrayIndex = i;
		}
	};
	this.listContacts = function(inCurrentTab){
		if(inCurrentTab == "xx"){
			return this.contacts;
		}else{
			var retArray = new Array();
			var start = inCurrentTab.substr(0,1).toUpperCase();
			var end = inCurrentTab.substr(1,1).toUpperCase();
			for(var i = 0;i < this.contacts.length;i++){
				var firstLetter = this.contacts[i].lastName.substr(0,1).toUpperCase();
				if(firstLetter >= start && firstLetter <= end){
					retArray.push(this.contacts[i]);
				}
			}
		}
		return retArray;
	}
	this.clearContacts = function(){
		dojox.storage.clear("");
		this.contacts = new Array();
	};
	this.getContact = function(inIndex){
		return this.contacts[inIndex];
	}
}
